package com.yishun.springboot.service.impl;


import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yinquan.util.ResultUtils;
import com.yishun.springboot.gwsutil.Elevator;
import com.yishun.springboot.mapper.*;
import com.yishun.springboot.pojo.*;
import com.yishun.springboot.service.GwsElevatorBasicInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * List<GwsElevatorProjectInfoDTO> projectInfos = gwsElevatorProjectInfoDTOMapper.findByProjectName(null, null);
 * 通过该方法控制推送XX工务署   null为所有工务署    1深证市工务署   2龙岗区工务署
 */

@Service
@Slf4j
@Configuration
public class GwsElevatorBasicInfoServiceImpl implements GwsElevatorBasicInfoService {

    @Resource
    Elevator elevator;

    @Resource
    GwsElevatorProjectInfoDTOMapper gwsElevatorProjectInfoDTOMapper;

    @Resource
    GwsElevatorBasicInfoMapper gwsElevatorBasicInfoMapper;

    @Resource
    IntelligentsiteCorrespondsMapper intelligentsiteCorrespondsMapper;

    @Resource
    GwsElevatorDataDTOMapper gwsElevatorDataDTOMapper;


    @Resource
    GwsLgqElevatorOperatorDTOMapper gwsLgqElevatorOperatorDTOMapper;


    @Resource
    GwsElevatorEnergisingDTOMapper energisingDTOMapper;

    /*
     * @param projectName          项目名称
     * @param action               防止基础信息成功，设备参数接口失败出死循环   默认：两个接口都发送   1、只发送基础信息  2、只发送设备参数
     * @return 00
     */
    @Override
    public JSONObject addGwsElevatorBasic(String projectName) {

        if (StringUtils.isEmpty(projectName)) {
            return ResultUtils.jsonFail("参数不能为空");
        }

        List<GwsElevatorProjectInfoDTO> projectInfos = gwsElevatorProjectInfoDTOMapper.findByProjectName(projectName, null);

        if (projectInfos == null || projectInfos.size() < 1) {
            return ResultUtils.jsonFail("需先上传项目信息");
        }
        GwsElevatorProjectInfoDTO gwsElevatorProjectInfoDTO = projectInfos.get(0);

        //传入头部参数
        String apiKey = gwsElevatorProjectInfoDTO.getApi_key();
        String engCode = gwsElevatorProjectInfoDTO.getEng_code();
        String projectCode = gwsElevatorProjectInfoDTO.getProject_code();
        String httpserver = gwsElevatorProjectInfoDTO.getGws_type_path();

        IntelligentsiteCorrespondsItemtable correspondsItemtable = intelligentsiteCorrespondsMapper.querySubjectByProjectName(projectName);

        Integer elevatorId = correspondsItemtable.getIntelligentsite_elevator_id();

        List<GwsElevatorBasicInfo> basicInfos = gwsElevatorBasicInfoMapper.getGwsBasic(elevatorId);

        List<String> devices = gwsElevatorBasicInfoMapper.findByGwsElevatorId(gwsElevatorProjectInfoDTO.getGws_elevator_id());


        if (basicInfos == null || basicInfos.size() == 0) {
            return ResultUtils.jsonSuccess("暂无需要对接条目");
        }

        List<String> errors = new ArrayList<String>();

        List<GwsElevatorBasicInfo> elevatorBasicInfos = new ArrayList<GwsElevatorBasicInfo>();

        for (GwsElevatorBasicInfo basicInfoList : basicInfos) {
            boolean isOk = devices.contains(basicInfoList.getDevice_code());

            //如果工务署基础信息表已包含该设备则不需要继续了
            if (isOk) {
                continue;
            }
            String device_no = UUID.randomUUID().toString().replace("-", "");
            //封装基础信息
            JSONObject jsonBasicInfo = new JSONObject();
            jsonBasicInfo.put("device_no", device_no);
            jsonBasicInfo.put("name", basicInfoList.getName());
            jsonBasicInfo.put("mon_device_man", basicInfoList.getMon_device_man());
            jsonBasicInfo.put("guangdong_install_num", basicInfoList.getGuangdong_install_num());

            JSONObject resBasic = elevator.addBasicInfo(jsonBasicInfo, httpserver, apiKey, engCode, projectCode);
            if (resBasic != null) {
                if (!("true").equals(resBasic.getString("result"))) {
                    errors.add("基础数据device_no：" + basicInfoList.getDevice_code() + "--msg：" + resBasic.getString("detail_message"));
                    continue;
                }
            }
            basicInfoList.setDevice_no(device_no);
            basicInfoList.setGws_elevator_id(gwsElevatorProjectInfoDTO.getGws_elevator_id());
            elevatorBasicInfos.add(basicInfoList);
        }

        int resDb;

        if (elevatorBasicInfos.size() > 0) {
            resDb = gwsElevatorBasicInfoMapper.addGwsElevatorBasicInfo(elevatorBasicInfos);

            if (resDb < 1) {
                return ResultUtils.jsonFail("数据库新增失败，请联系管理员手动添加");
            }
        }
        if (errors.size() > 0) {
            JSONArray errorJsonArr = JSONArray.parseArray(JSON.toJSONString(errors));
            return ResultUtils.jsonFail(errorJsonArr.toJSONString());
        }
        return ResultUtils.jsonSuccess();
    }

    @Override
    public JSONObject addGwsElevatorParams(String projectName) {

        if (StringUtils.isEmpty(projectName)) {
            return ResultUtils.jsonFail("参数不能为空");
        }

        List<GwsElevatorProjectInfoDTO> projectInfos = gwsElevatorProjectInfoDTOMapper.findByProjectName(projectName, null);

        if (projectInfos == null || projectInfos.size() < 1) {
            return ResultUtils.jsonFail("需先上传项目信息");
        }
        GwsElevatorProjectInfoDTO gwsElevatorProjectInfoDTO = projectInfos.get(0);

        //传入头部参数
        //传入头部参数
        String apiKey = gwsElevatorProjectInfoDTO.getApi_key();
        String engCode = gwsElevatorProjectInfoDTO.getEng_code();
        String projectCode = gwsElevatorProjectInfoDTO.getProject_code();
        String httpserver = gwsElevatorProjectInfoDTO.getGws_type_path();

        List<String> errors = new ArrayList<String>();

        IntelligentsiteCorrespondsItemtable correspondsItemtable = intelligentsiteCorrespondsMapper.querySubjectByProjectName(projectName);

        Integer elevatorId = correspondsItemtable.getIntelligentsite_elevator_id();

        List<GwsElevatorBasicInfo> basicInfos = gwsElevatorBasicInfoMapper.getGwsParams(elevatorId);

        if (basicInfos == null || basicInfos.size() == 0) {
            return ResultUtils.jsonSuccess("暂无需要对接条目");
        }

        for (GwsElevatorBasicInfo basicInfo : basicInfos) {
            String device_no = basicInfo.getDevice_no();
            JSONObject jsonBasicInfo = new JSONObject();

            jsonBasicInfo.put("device_no", device_no);
            jsonBasicInfo.put("L_Height", basicInfo.getL_Height());
            jsonBasicInfo.put("L_Load_Capacity", basicInfo.getL_Load_Capacity());

            JSONObject resBasic = elevator.addParams(jsonBasicInfo, httpserver, apiKey, engCode, projectCode);

            if (resBasic != null) {
                if (!("true").equals(resBasic.getString("result"))) {
                    errors.add("参数信息device_no：" + device_no + "--msg：" + resBasic.getString("message"));
                    continue;
                }
            }
            Integer resDb = gwsElevatorBasicInfoMapper.updateGwsParams(basicInfo);

            if (resDb < 1) {
                errors.add("device_no：" + device_no + "--msg：数据库新增失败");
            }
        }
        if (errors.size() > 0) {
            JSONArray errorJsonArr = JSONArray.parseArray(JSON.toJSONString(errors));
            return ResultUtils.jsonFail(errorJsonArr.toJSONString());
        }
        return ResultUtils.jsonSuccess();
    }

    @Async(value = "asyncExecutor")
    @Scheduled(fixedRate = 1000 * 20)
    @Override
    public void timingPushElevatorData() {
        List<GwsElevatorProjectInfoDTO> projectInfos = gwsElevatorProjectInfoDTOMapper.findByProjectName(null, null);

        for (GwsElevatorProjectInfoDTO projectInfo : projectInfos) {

            Integer elevatorId = projectInfo.getGws_elevator_id();

            String apiKey = projectInfo.getApi_key();
            String engCode = projectInfo.getEng_code();
            String projectCode = projectInfo.getProject_code();
            String httpserver = projectInfo.getGws_type_path();

            List<GwsElevatorDataDTO> elevatorData = gwsElevatorDataDTOMapper.findByGwsElevatorId(elevatorId);

            for (GwsElevatorDataDTO elevatorDataDTO : elevatorData) {

                JSONObject paramJson = JSONObject.parseObject(JSONObject.toJSONString(elevatorDataDTO));

                elevator.pushElevatorData(paramJson, httpserver, apiKey, engCode, projectCode);
            }
        }
    }


    @Async(value = "asyncExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 60)
    @Override
    public void timingPushElevatorOperator() {
        List<GwsElevatorProjectInfoDTO> projectInfos = gwsElevatorProjectInfoDTOMapper.findByProjectName(null, null);

        for (GwsElevatorProjectInfoDTO projectInfo : projectInfos) {

            Integer elevatorId = projectInfo.getGws_elevator_id();
            //传入头部参数
            String apiKey = projectInfo.getApi_key();
            String engCode = projectInfo.getEng_code();
            String projectCode = projectInfo.getProject_code();
            String httpserver = projectInfo.getGws_type_path();

            List<GwsLgqElevatorOperatorDTO> gwsLgqElevatorOperatorDTOS = gwsLgqElevatorOperatorDTOMapper.findEachDeviceNewOperator(elevatorId);

            for (GwsLgqElevatorOperatorDTO elevatorOperatorDTO : gwsLgqElevatorOperatorDTOS) {

                JSONObject paramJson = JSONObject.parseObject(JSONObject.toJSONString(elevatorOperatorDTO));

                elevator.pushElevatorOperator(paramJson, httpserver, apiKey, engCode, projectCode);
            }
        }
    }

    @Async(value = "asyncExecutor")
    @Scheduled(fixedRate = 1000 * 60)
    @Override
    public void flushElevatorState() {
        List<GwsElevatorProjectInfoDTO> projectInfos = gwsElevatorProjectInfoDTOMapper.findByProjectName(null, null);

        for (GwsElevatorProjectInfoDTO projectInfo : projectInfos) {

            Integer elevatorId = projectInfo.getGws_elevator_id();
            //传入头部参数
            String apiKey = projectInfo.getApi_key();
            String engCode = projectInfo.getEng_code();
            String projectCode = projectInfo.getProject_code();
            String httpserver = projectInfo.getGws_type_path();


            List<GwsElevatorEnergisingDTO> elevatorEnergisingDTOS = energisingDTOMapper.findByGwsElevatorId(elevatorId);

            for (GwsElevatorEnergisingDTO elevatorEnergisingDTO : elevatorEnergisingDTOS) {

                JSONObject paramJson = JSONObject.parseObject(JSONObject.toJSONString(elevatorEnergisingDTO));

                elevator.pushElevatorEnergising(paramJson, httpserver, apiKey, engCode, projectCode);
            }
        }
    }

    @Async(value = "asyncExecutor")
    @Scheduled(cron = "00 00 23 * * ?")
    @Override
    public void flushElevatorSwitchTime() {
        List<GwsElevatorProjectInfoDTO> projectInfos = gwsElevatorProjectInfoDTOMapper.findByProjectName(null, 1);

        for (GwsElevatorProjectInfoDTO projectInfo : projectInfos) {

            Integer elevatorId = projectInfo.getGws_elevator_id();
            //传入头部参数
            String apiKey = projectInfo.getApi_key();
            String engCode = projectInfo.getEng_code();
            String projectCode = projectInfo.getProject_code();
            String httpserver = projectInfo.getGws_type_path();

            List<GwsElevatorEnergisingDTO> elevatorEnergisingDTOS = energisingDTOMapper.findByGwsElevatorId(elevatorId);

            JSONObject paramJson = new JSONObject();




            elevator.pushElevatorEnergising(paramJson, httpserver, apiKey, engCode, projectCode);
        }
    }
}
